package com.cq.controller;

import com.alibaba.fastjson.JSONObject;
import com.cq.pojo.TbUser;
import com.cq.pojo.vo.UserVO;
import com.cq.result.ContentResult;
import com.cq.result.Result;
import com.cq.service.UserService;
import com.cq.utils.JwtUtil;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping("/login")
public class LoginController {

    @Autowired
    private UserService userService;
    @Autowired
    private JwtUtil jwtUtil;

    @PostMapping("/login")
    public Result login(String username, String password) {
        // 获取subject对象
        Subject subject = SecurityUtils.getSubject();
        // 创建token对象
        UsernamePasswordToken usernamePasswordToken = new UsernamePasswordToken(username, password);

        // 调用login方法
        try {
            subject.login(usernamePasswordToken);
        } catch (AuthenticationException e) {
            e.printStackTrace();
            return new Result<>(ContentResult.LOGIN_ERROR_CODE, ContentResult.LOGIN_ERROR, null);
        }

        // 生成token
        TbUser principal = (TbUser) subject.getPrincipal();
        UserVO user = new UserVO();
        BeanUtils.copyProperties(principal, user);
        String token = jwtUtil.createJwt(user.getId().toString(), JSONObject.toJSONString(user), "userRoles");
        return new Result<>(ContentResult.LOGIN_SUCCESS_CODE, ContentResult.LOGIN_SUCCESS, token);
    }
}
